const fs = require("fs");
const path = require("path");
const parser = require("@babel/parser");
const types = require("@babel/types");
const generator = require("@babel/generator").default;

// 定义正则表达式来匹配中文字符
const chineseRegex = /[\u4e00-\u9fa5]/g;
//path
const sourcePath = "/Users/hrtps/workSpace/theseus-careers-wechat/src";
// 定义一个函数来检查给定的AST节点是否包含中文字符
function containsChinese(node) {
  if (types.isStringLiteral(node)) {
    return node.value.match(chineseRegex);
  }
  for (const key in node) {
    if (node.hasOwnProperty(key) && typeof node[key] === "object") {
      const childNode = node[key];
      if (containsChinese(childNode)) {
        return true;
      }
    }
  }
  return false;
}

// 定义一个函数来遍历AST，并提取包含中文字符的节点信息
function extractChineseFromAST(ast) {
  const result = [];
  function traverse(node, parent) {
    result.push({
      file: parent ? parent.source : null,
      text: generator(types.cloneNode(node)).code,
    });
    for (const key in node) {
      if (node.hasOwnProperty(key) && typeof node[key] === "object") {
        const childNode = node[key];
        traverse(childNode, node);
      }
    }
  }
  traverse(ast);
  return result;
}

// 定义一个函数来读取文件并将其转换为AST
function parseFile(filePath) {
  const fileContent = fs.readFileSync(filePath, "utf-8");
  const ast = parser.parse(fileContent, {
    sourceType: "module",
    plugins: ["jsx", "typescript"],
  });
  return ast;
}

// 定义一个函数来将提取到的中文字符存储为JSON文件
function saveToJSONFile(data, outputPath) {
  fs.writeFileSync(outputPath, JSON.stringify(data, null, 2));
}

// 主函数，用于执行整个流程
async function main() {
  const srcFolderPath = path.join(__dirname, "src"); // 替换为你的项目src文件夹路径
  const files = fs.readdirSync(srcFolderPath);
  const astData = [];
  for (const file of files) {
    const filePath = path.join(srcFolderPath, file);
    const ast = parseFile(filePath);
    const chineseNodes = extractChineseFromAST(ast);
    astData.push(...chineseNodes);
  }
  const outputPath = path.join(__dirname, "chinese.json"); // 替换为你希望保存JSON文件的路径
  saveToJSONFile(astData, outputPath);
  console.log(`中文字符已保存到${outputPath}`);
}
main().catch(console.error);
